import React, { useCallback, useEffect } from 'react';

import { SvgIcon } from '@/components/icon';

import { EditorVariablePickerType } from '../../type';

export default function DropDownMenu({
  variables,
  setDropdownValue,
}: {
  variables: EditorVariablePickerType[];
  setDropdownValue?: (value: string) => void;
}) {
  const [highlightedIndex, setHighlightedIndex] = React.useState(0);

  const handleKeyDown = useCallback(
    (event: any) => {
      if (event.keyCode === 38) {
        setHighlightedIndex((prevIndex) => Math.max(prevIndex - 1, 0));
      } else if (event.keyCode === 40) {
        setHighlightedIndex((prevIndex) => Math.min(prevIndex + 1, variables.length - 1));
      } else if (event.keyCode === 13 && variables[highlightedIndex]?.key) {
        setDropdownValue?.(variables[highlightedIndex].key);
      }
    },
    [highlightedIndex, setDropdownValue, variables],
  );

  useEffect(() => {
    document.addEventListener('keydown', handleKeyDown);

    return () => {
      document.removeEventListener('keydown', handleKeyDown);
    };
  }, [handleKeyDown]);

  return variables.length ? (
    <div
      className="absolute top-full max-h-[300px] w-auto overflow-auto rounded-md border border-bgBase bg-white p-2 shadow-lg"
      style={{
        maxHeight: '300px',
        zIndex: 99999,
      }}
    >
      {variables.map((item, index) => (
        <div
          className={`flex cursor-pointer items-center overflow-auto rounded-sm px-4 py-2 ${
            index === variables.length - 1 ? '' : 'mb-2'
          } ${
            highlightedIndex === index ? 'bg-gray-500 text-primary-600' : 'bg-white text-gray-600'
          }`}
          style={{
            maxHeight: '300px',
          }}
          key={item.key}
          onMouseDown={(e) => {
            e.preventDefault();

            setDropdownValue?.(item.key);
          }}
          onMouseEnter={() => {
            setHighlightedIndex(index);
          }}
        >
          <SvgIcon icon={(item.icon as any) || 'variable'} />
          <div className="ml-2 text-sm">
            {item.key}
            {item.key !== item.label && `(${item.label})`}
          </div>
        </div>
      ))}
    </div>
  ) : null;
}
